import axios from 'axios'
import Router from '../router/index'
import { Message } from 'element-ui'

let Axios = axios.create({
  timeout: 15000,
  responseType: 'json',
  // withCredentials: true, // 是否允许带cookie这些
  headers: {
    // "Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
    // "Content-Type": "application/x-www-form-urlencoded",
    'Content-Type': 'application/json;charset=utf-8'
  }
})
// 535983654
const $url = 'http://120.27.18.161:8889'
// const $url = 'http://192.168.111.12:8889'
//  const $url = 'http://192.168.11.113:8889'
// const $url = 'http://192.168.10.36:8889'

if (process.env.NODE_ENV === 'development') {
    Axios.defaults.baseURL = $url;
} else if (process.env.NODE_ENV === 'debug') {
    Axios.defaults.baseURL = $url;
} else if (process.env.NODE_ENV === 'production') {
    Axios.defaults.baseURL = $url;
}

// Axios.defaults.withCredentials = true;
// Axios.defaults.transformRequest = [function(data) {
//   //数据序列化
//   return qs.stringify(data);
// }];
//在发送请求之前做某事
Axios.interceptors.request.use(
  config => {
    if (localStorage.getItem('authToken')) {
      // console.log(localStorage.getItem('authToken'));
      config.headers['authToken'] = localStorage.getItem('authToken')
    }
    // console.log('this is axios config>>>', config)
    return config
  },
  error => {
    // error的回调信息，可定义
    console.error('Axios.interceptors',error)
    return Promise.reject(error)
  }
)

// 返回状态判断(添加响应拦截器)
Axios.interceptors.response.use(
  response => {
    const res = response
      // console.log('res-1', res)

      if (res.status !== 200) {
      console.log('res', res)
    }else if(res.status === 500) {
        Message.error('网络连接超时...')
    }
    if(res.data.code == -1){
        Router.push({ path: '/login' })
        // Message.error('连接超时，请重新登录...')
    }
    return Promise.resolve(res.data)
  },
  error => {
    console.log('err', error) // for debug
    Message.error('网络请求失败...')
    return Promise.reject(error)
  }
)

export{
  Axios,
  $url
};
